<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        var Tool = {
            ajax: function (obj) {
                return new Promise(function (resolve, reject) {
                    var url = obj.url || location.href;
                    var type = obj.type || 'get';
                    var data = this.getParam(obj.data);
                    var callback = obj.callback;
                    var xhr = new XMLHttpRequest();
                    if (type == 'get') {
                        url = url + '?' + data;
                        data = null;
                    }
                    xhr.open(type, url);
                    if (type == 'post') {
                        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
                    }
                    xhr.send(data);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            var r = xhr.responseText;
                            //在promise中，如果想要调用.then中传递的成功的回调
                            //只需要将当前promise标记为fulfilled
                            resolve(r);
                        }
                    };
                })
            },
            getParam: function (object) {
                var str = '';
                for (var k in object) {
                    str += k + "=" + object[k] + "&";
                }
                str = str.substr(0, str.length - 1);
                console.log(str);
                return str;
            }
        };


        Tool.ajax({
            url: './02-ajax-post.php',
            type: 'post',
            data: {
                name: '琪琪'
            }
        }).then(function (data) {
            alert("heihei")
        })
        Tool.getParam({ name: '琪琪' });

    </script>
</body>

</html>